package com.example.homework.ui.main

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.homework.R
import com.example.homework.databinding.FragmentMainBinding
import com.example.homework.viewmodels.MainViewModel
import kotlinx.coroutines.launch

class Main : Fragment() {
    private var _binidng: FragmentMainBinding? = null
    private val binding: FragmentMainBinding
        get() = _binidng!!
    private val viewModel: MainViewModel by viewModels<MainViewModel>()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binidng = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        lifecycleScope.launch {
            launch {
                viewModel.dataFlow.collect { data ->
                    if (data != null)
                        with(binding) {
                            userName.text =
                                getString(R.string.user_name, data.results.first().name.first)
                            userEmail.text =
                                getString(R.string.user_email, data.results.first().email)
                            userLocation.text = getString(
                                R.string.user_location,
                                data.results.first().location.city
                            )
                            userGender.text =
                                getString(R.string.user_gender, data.results.first().gender)
                            userPhone.text =
                                getString(R.string.user_phone, data.results.first().phone)
                            Glide.with(requireView()).load(data.results.first().picture.medium)
                                .into(userImage)
                        }
                }
            }
            launch {
                viewModel.uiState.collect {
                    with(binding) {
                        refreshButton.isEnabled = it.isButtonEnabled
                        loadingProgress.isVisible = it.isProgressVisible
                    }
                }
            }
        }
        binding.refreshButton.setOnClickListener {
            viewModel.updateData()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binidng = null
    }
}